import rclpy
from rclpy.node import Node
import time
import espeakng
from queue import Queue
from example_interfaces.msg import String
import threading

class NovelSubNode(Node):
    def __init__ (self,node_name):
        Node.__init__(self,node_name)
        self.get_logger().info(f"{node_name}已经开始订阅")
        self.queue = Queue()
        self.subscriber = self.create_subscription(String,"novel",self.novel_callback,10)
        self.sepeak_thread = threading.Thread(target=self.speak_novel)
        self.running1 = True  # 判断是否开启线程
        self.sepeak_thread.start()  # 启动线程
        
    def novel_callback(self,msg):
        self.queue.put(msg.data)  # 将消息放入队列
        
    def speak_novel(self):
        speaker = espeakng.Speaker()
        speaker.voice = 'zh-CN'
        while self.running1:
            if not self.queue.empty():
                novel = self.queue.get()
                self.get_logger().info(f"{novel}")
                speaker.say(novel)
                speaker.wait()
            else:
                time.sleep(1)
    def destroy_node(self):    #  重写父类的销毁节点方法
        self.running1 = False
        self.sepeak_thread.join()
        super().destroy_node()

def main():
    rclpy.init()
    node = NovelSubNode("novel_sub")
    rclpy.spin(node)
    rclpy.shutdown()